const WXAPI = require('../../Wxapi/api.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  bindGetUserInfo: function (e) {
    let that = this;
    console.log(!e.detail.userInfo)
    if (!e.detail.userInfo) {
      wx.switchTab({
        url: '/pages/index/index'
      })
      return false
    }
    that.login()
  },
  login: function () {
    let that = this;
    wx.login({
      success: function (res) {
        WXAPI.getUserInfo({
          code: res.code
        }).then(function (res) {
          if (res.code == 200) {
            console.log("用户已存在", res)
            wx.setStorageSync("uid", res.user_info.id);
            wx.setStorageSync("openId", res.user_info.openId)
            wx.getUserInfo({
              success: function (res) {
                console.log("获取用户信息并设置缓存:", res.userInfo)
                wx.setStorageSync("userInfo", res.userInfo)
              },
              complete: function (){
                // 回跳
                wx.hideLoading()
                wx.navigateBack()
              }
            })
          } else if (res.code == 201) {
            console.log("用户注册");
            // 注册用户
            that.registerUser(res.openId)
          }
          
        })
      }
    })
  },
  // 注册
  registerUser: function (openId) {
    let that = this;
    console.log("开始正式注册")
    wx.login({
      success: function (res) {
        let code = res.code; // 微信登录接口返回的 code 参数，下面注册接口需要用到
        wx.getUserInfo({
          success: function (res) {
            let avatarUrl = res.userInfo.avatarUrl,
              nickName = res.userInfo.nickName,
              gender = res.userInfo.gender,
              country = res.userInfo.country,
              province = res.userInfo.province,
              city = res.userInfo.city
            // 下面开始调用注册接口
            WXAPI.register({
              avatarUrl: avatarUrl,
              nickName: nickName,
              openId: openId,
              gender: gender,
              country: country,
              province: province,
              city: city,
            }).then(function (res) {
              that.login()
            })
          }
        })
      }
    })
  }
})